<?php

namespace App\Http\Controllers;

use App\Models\FeelingTone;
use App\Models\FeelingToneComment;
use App\Models\Project;
use App\Models\Team;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class FeelingToneController extends Controller
{
    public function index(Request $request)
    {
        $perPage = $request->get('perPage', 10);
        $query = FeelingTone::with(['author', 'project', 'team']);
        $user = $request->user();

        $query->where('feeling_tone.is_display', '=', '1');

        if ($user->type == 4) {
            if (!$request->has('org_id')) {
                throw new \Exception('请指定机构信息');
            }

            $query->where('feeling_tone.org_id', '=', $request->get('org_id'));
        } else if ($user->type == 3) {
            $query->where('feeling_tone.org_id', '=', $user->org_id);
        } else if ($user->type == 2) {
            if (!$user->team->auth_create_team) {
                throw new \Exception('没权限');
            }

            $query->where(function($query) use ($user) {
                $query->orWhere(function($query) use ($user) {
                    $query->where('feeling_tone.relation_id', '=', $user->team->id);
                    $query->where('feeling_tone.type', '=', '3');
                });

                $projectIds = [];
                foreach(Project::where('team_id', '=', $user->team->id)->select('id')->get() as $project) {
                    $projectIds[] = $project->id;
                }

                $query->orWhere(function($query) use ($user) {
                    $query->where('feeling_tone.relation_id', '=', $user->team->id);
                    $query->where('feeling_tone.type', '=', '3');
                });

                $query->orWhere(function($query) use ($projectIds) {
                    $query->whereIn('feeling_tone.relation_id', $projectIds);
                    $query->where('feeling_tone.type', '=', '2');
                });
            });
        }

        if ($request->has('author')) {
            $query->join('user', 'user.id', '=', 'feeling_tone.user_id')
                ->where(function($query) use ($request) {
                    $query->where('user.username', 'like', '%' .$request->get('author'). '%');
                    $query->orWhere('user.phone', 'like', '%' .$request->get('author'). '%');
                });
        }

        if ($request->has('keywords')) {
            $projectIds = [];

            foreach(Project::where('name', 'like', '%' .$request->get('keywords'). '%')
                        ->select('id')
                        ->get() as $project) {
                $projectIds[] = $project->id;
            };

            $teamIds = [];
            foreach(Team::where('name', 'like', '%' .$request->get('keywords'). '%')
                        ->select('id')
                        ->get() as $team) {
                $teamIds[] = $team->id;
            };

            $query->where(function($query) use($projectIds, $teamIds) {
                count($projectIds) && $query->orWhere(function($query) use ($projectIds) {
                    $query->whereIn('feeling_tone.relation_id', $projectIds);
                    $query->where('feeling_tone.type', '=', '2');
                });


                count($teamIds) && $query->orWhere(function($query) use ($teamIds) {
                    $query->where('feeling_tone.type', '=', '3');
                    $query->whereIn('feeling_tone.relation_id', $teamIds);
                });
            });
        }

        if ($request->has('start_time')) {
            $query->where('feeling_tone.created_at', '>=', date('Y-m-d H:i:s', $request->get('start_time')));
        }

        if ($request->has('end_time')) {
            $query->where('feeling_tone.created_at', '<=', date('Y-m-d H:i:s', $request->get('end_time')));
        }

        $query->select(DB::Raw('feeling_tone.*'));
        $query->orderBy('feeling_tone.created_at', 'desc');
        $info = $query->paginate($perPage)->toArray();

        return $this->returnJSON([
            'count' => $info['total'],
            'rows' => $info['data']
        ]);
    }

    public function destroy(Request $request, $id)
    {
        $ids = array_map(function($item) {
            return intval($item);
        }, explode(",", $id));

        if (FeelingTone::whereIn('id', $ids)->update(['is_display' => '0'])) {
            return $this->returnJSON($ids, 0, '删除成功');
        } else {
            return $this->returnJSON(null, 1, "删除失败");
        }
    }

    public function comments(Request $request)
    {
        $perPage = $request->get('perPage', 10);
        $query = FeelingToneComment::with(['author', 'post.author']);
        $user = $request->user();


        $query->where('feeling_tone_comment.is_display', '=', '1');

        if ($user->type == 4) {
            if (!$request->has('org_id')) {
                throw new \Exception('请指定机构信息');
            }

            $query->join('feeling_tone', 'feeling_tone.id', '=', 'feeling_tone_comment.feeling_id')
                    ->where('feeling_tone.org_id', '=', $request->get('org_id'));
        } else if ($user->type == 3) {
            $query->join('feeling_tone', 'feeling_tone.id', '=', 'feeling_tone_comment.feeling_id')
                ->where('feeling_tone.org_id', '=',  $user->org_id);
        } else if ($user->type == 2) {
            if (!$user->team->auth_create_team) {
                throw new \Exception('没权限');
            }

            $query->join('feeling_tone', 'feeling_tone.id', '=', 'feeling_tone_comment.feeling_id');

            $query->where(function($query) use ($user) {
                $query->orWhere(function($query) use ($user) {
                    $query->where('feeling_tone.relation_id', '=', $user->team->id);
                    $query->where('feeling_tone.type', '=', '3');
                });

                $projectIds = [];
                foreach(Project::where('team_id', '=', $user->team->id)->select('id')->get() as $project) {
                    $projectIds[] = $project->id;
                }

                $query->orWhere(function($query) use ($user) {
                    $query->where('feeling_tone.relation_id', '=', $user->team->id);
                    $query->where('feeling_tone.type', '=', '3');
                });

                $query->orWhere(function($query) use ($projectIds) {
                    $query->whereIn('feeling_tone.relation_id', $projectIds);
                    $query->where('feeling_tone.type', '=', '2');
                });
            });
        }

        if ($request->has('fid')) {
            $query->where('feeling_tone_comment.feeling_id', '=', $request->get('fid'));
        }

        if ($request->has('author')) {
            $query->join('user', 'user.id', '=', 'feeling_tone_comment.user_id')
                ->where(function($query) use ($request) {
                    $query->where('user.username', 'like', '%' .$request->get('author'). '%');
                    $query->orWhere('user.phone', 'like', '%' .$request->get('author'). '%');
                });
        }

        if ($request->has('start_time')) {
            $query->where('feeling_tone_comment.created_at', '>=', date('Y-m-d H:i:s', $request->get('start_time')));
        }

        if ($request->has('end_time')) {
            $query->where('feeling_tone_comment.created_at', '<=', date('Y-m-d H:i:s', $request->get('end_time')));
        }

        $query->select(DB::Raw('feeling_tone_comment.*'));

        $query->orderBy('feeling_tone_comment.created_at', 'desc');
        $info = $query->paginate($perPage)->toArray();


        return $this->returnJSON([
            'count' => $info['total'],
            'rows' => $info['data']
        ]);
    }

    public function replies(Request $request)
    {
        $perPage = $request->get('perPage', 10);
        $query = FeelingToneComment::with(['author', 'post.author']);
        $user = $request->user();


        $query->where('feeling_tone_comment.is_display', '=', '1');

        if ($user->type == 4) {
            if (!$request->has('org_id')) {
                throw new \Exception('请指定机构信息');
            }

            $query->join('feeling_tone', 'feeling_tone.id', '=', 'feeling_tone_comment.feeling_id')
                ->where('feeling_tone.org_id', '=', $request->get('org_id'));
        } else if ($user->type == 3) {
            $query->join('feeling_tone', 'feeling_tone.id', '=', 'feeling_tone_comment.feeling_id')
                ->where('feeling_tone.org_id', '=',  $user->org_id);
        } else if ($user->type == 2) {
            if (!$user->team->auth_create_team) {
                throw new \Exception('没权限');
            }

            $query->join('feeling_tone', 'feeling_tone.id', '=', 'feeling_tone_comment.feeling_id');

            $query->where(function($query) use ($user) {
                $query->orWhere(function($query) use ($user) {
                    $query->where('feeling_tone.relation_id', '=', $user->team->id);
                    $query->where('feeling_tone.type', '=', '3');
                });

                $projectIds = [];
                foreach(Project::where('team_id', '=', $user->team->id)->select('id')->get() as $project) {
                    $projectIds[] = $project->id;
                }

                $query->orWhere(function($query) use ($user) {
                    $query->where('feeling_tone.relation_id', '=', $user->team->id);
                    $query->where('feeling_tone.type', '=', '3');
                });

                $query->orWhere(function($query) use ($projectIds) {
                    $query->whereIn('feeling_tone.relation_id', $projectIds);
                    $query->where('feeling_tone.type', '=', '2');
                });
            });
        }

        if ($request->has('fid')) {
            $query->where('feeling_tone_comment.feeling_id', '=', $request->get('fid'));
        }

        if ($request->has('author')) {
            $query->join('user', 'user.id', '=', 'feeling_tone_comment.user_id')
                ->where(function($query) use ($request) {
                    $query->where('user.username', 'like', '%' .$request->get('author'). '%');
                    $query->orWhere('user.phone', 'like', '%' .$request->get('author'). '%');
                });
        }

        if ($request->has('start_time')) {
            $query->where('feeling_tone_comment.created_at', '>=', date('Y-m-d H:i:s', $request->get('start_time')));
        }

        if ($request->has('end_time')) {
            $query->where('feeling_tone_comment.created_at', '<=', date('Y-m-d H:i:s', $request->get('end_time')));
        }

        $query->select(DB::Raw('feeling_tone_comment.*'));

        $query->orderBy('feeling_tone_comment.created_at', 'desc');
        $info = $query->paginate($perPage)->toArray();


        return $this->returnJSON([
            'count' => $info['total'],
            'rows' => $info['data']
        ]);
    }

    public function reply(Request $request) {
        $comment = FeelingToneComment::findOrFail($request->input('id'));
        $user = $request->user();

        $node = new FeelingToneComment();
        $node->fill([
            'user_id' => $user->id,
            'feeling_id' => $comment->feeling_id,
            'parent_id' => $comment->id,
            'comment' => $request->input('content'),
            'is_display' => '1'
        ]);
        if ($node->save()) {
            $feelingTone = $comment->feeling;
            $feelingTone->fill([
                'comment_count' => FeelingToneComment::where('feeling_id', '=', $feelingTone->id)
                    ->where('is_display', '=', '1')->count()
            ]);
            $feelingTone->save();

            return $this->returnJSON(null, 0, '回复成功');
        }
        return $this->returnJSON(null, 500, '回复失败');
    }

    public function comment(Request $request) {
        $feelingTone = FeelingTone::findOrFail($request->input('id'));
        $user = $request->user();

        $node = new FeelingToneComment();
        $node->fill([
            'user_id' => $user->id,
            'feeling_id' => $feelingTone->id,
            'parent_id' => '0',
            'comment' => $request->input('content'),
            'is_display' => '1'
        ]);
        if ($node->save()) {
            $feelingTone->fill([
                'comment_count' => FeelingToneComment::where('feeling_id', '=', $feelingTone->id)
                    ->where('is_display', '=', '1')->count()
            ]);
            $feelingTone->save();
            return $this->returnJSON(null, 0, '回复成功');
        }
        return $this->returnJSON(null, 500, '回复失败');
    }

    public function destroyComment(Request $request, $id)
    {
        $ids = array_map(function($item) {
            return intval($item);
        }, explode(",", $id));

        if (FeelingToneComment::whereIn('id', $ids)->update(['is_display' => '0'])) {
            $feelingIds = [];
            foreach(FeelingToneComment::select('feeling_id')->whereIn('id', $ids)->get() as $item) {
                $feelingIds[] = $item->feeling_id;
            }

            foreach(FeelingTone::whereIn('id', $feelingIds)->get() as $feeling) {
                $feeling->fill([
                    'comment_count' => FeelingToneComment::where('feeling_id', '=', $feeling->id)->where('is_display', '=', '1')->count()
                ]);
                $feeling->save();
            }

            return $this->returnJSON($ids, 0, '删除成功');
        } else {
            return $this->returnJSON(null, 1, "删除失败");
        }
    }
}
